package com.example.linearlayoutdemo;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.linearlayoutdemo.avatar.ProfileViewModel;
import com.example.linearlayoutdemo.avatar.UserManager;
import com.example.linearlayoutdemo.startservice.GpsCsvService;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MineFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MineFragment extends Fragment {

    private String email;
    private TextView emailTextView;
    private TextView interestTextView;
    private Button selButton;
    private Button exitButton;
    private Button bookButton;
    private Button gpsButton;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    // 1. 声明ViewModel（从MainActivity获取）
    private UserViewModel userViewModel;

    private ImageView ivAvatar;
    private ProfileViewModel profileViewModel;
    // 1. 声明权限申请器（用于动态申请存储权限）
    private ActivityResultLauncher<String> permissionLauncher;
    // 2. 声明相册选择器（之前已实现，此处复用）
    private ActivityResultLauncher<String> galleryLauncher;

    private static final String TAG = "MineFragment";

    public MineFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MineFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MineFragment newInstance(String param1, String param2) {
        MineFragment fragment = new MineFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: Fragment创建");
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Log.d(TAG, "onCreateView: 创建视图");
        View view =  inflater.inflate(R.layout.fragment_mine, container, false);
        emailTextView = view.findViewById(R.id.tv_email);
        interestTextView =  view.findViewById(R.id.tv_interest);
        selButton =  view.findViewById(R.id.btn_select);
        exitButton =  view.findViewById(R.id.btn_exit);
        bookButton =  view.findViewById(R.id.btn_book);
        gpsButton =  view.findViewById(R.id.btn_bindgps);

        // 初始化视图
        ivAvatar = view.findViewById(R.id.iv_avatar);

        //取头像

        ActivityResultLauncher<String> galleryLauncher = registerForActivityResult(
                new ActivityResultContracts.GetContent(),  // 内置合约：获取内容（如图片）
                new ActivityResultCallback<Uri>() {
                    @Override
                    public void onActivityResult(Uri o) {
                        if (o != null) {
                            displayImageFromUri(o, ivAvatar);
                            // 保存选择的头像
                            profileViewModel.saveNewAvatar(o);
                        }
                    }
                }
        );
        // 3. 初始化权限申请器
        initPermissionLauncher();
        // 4. 初始化相册选择器（之前的代码，保持不变）
        initGalleryLauncher();

        // 5. 头像点击事件：先检查权限，再打开相册
        ivAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPermissionAndOpenGallery();
            }
        });


//        email = getIntent().getStringExtra("email");

        // 4. 从MainActivity获取ViewModel（核心：拿到共享数据）
        userViewModel = ((HomeActivity) getActivity()).getUserViewModel();

        emailTextView.setText("Email:"+userViewModel.getUserEmail());
        interestTextView.setText("我的兴趣：" + userViewModel.getUserInterest());
        // 1. 注册回调：接收从InterestActivity返回的数据
        ActivityResultLauncher<Intent> interestLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        // 校验结果是否有效（RESULT_OK表示目标页面成功返回数据）
                        if (result.getResultCode() == RESULT_OK) {
                            Intent data = result.getData();
                            if (data != null) {
                                // 获取回传的兴趣数据
                                String selectedInterest = data.getStringExtra("selectedInterests");
                                // 关键：把结果存到ViewModel（而不是只改TextView）
                                userViewModel.setUserInterest(selectedInterest);
                                // 显示在主页
                                interestTextView.setText("我的兴趣：" + selectedInterest);
                            }
                        }
                    }
                }
        );

        UserManager.getInstance().setCurrentUserId(userViewModel.getUserEmail());

        // 初始化ViewModel
        profileViewModel = new ViewModelProvider(this).get(ProfileViewModel.class);
        // 观察头像数据变化
        profileViewModel.getAvatarLiveData().observe(getViewLifecycleOwner(), bitmap -> {
            if (bitmap != null) {
                ivAvatar.setImageBitmap(bitmap);
            }
        });
        // 观察错误信息
        profileViewModel.getErrorLiveData().observe(getViewLifecycleOwner(), errorMsg -> {
            if (errorMsg != null) {
                Toast.makeText(getContext(), errorMsg, Toast.LENGTH_SHORT).show();
            }
        });
        // 加载当前用户头像
        profileViewModel.loadCurrentUserAvatar();

        selButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), InterestActivity.class);
                //startActivityForResult(intent, 1);
                interestLauncher.launch(intent);
            }
        });
        exitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(getActivity())
                        .setTitle("提示")
                        .setMessage("确定要退出登录吗？")
                        .setCancelable(true)
                        .setPositiveButton("确定", (dialog, which) -> {
                            // 确认后执行默认返回操作（销毁Activity）
                            dialog.dismiss();
                            Intent intent = new Intent(getActivity(), MainActivity.class);
                            //
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);

                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });
        bookButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), BookActivity.class);
                //
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("email", userViewModel.getUserEmail());
                startActivity(intent);
            }
        });
        // 2. 开始保存按钮
        view.findViewById(R.id.btn_startgps).setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), GpsCsvService.class);
            intent.putExtra("COMMAND", "START_SAVE");
            getActivity().startService(intent);
            Toast.makeText(getActivity(), "开始保存 GPS 数据", Toast.LENGTH_SHORT).show();
        });

        // 3. 停止保存按钮
        view.findViewById(R.id.btn_stopgps).setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), GpsCsvService.class);
            intent.putExtra("COMMAND", "STOP_SAVE");
            getActivity().startService(intent);
            Toast.makeText(getActivity(), "停止保存 GPS 数据", Toast.LENGTH_SHORT).show();
        });
        gpsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), GpsActivity.class);
                startActivity(intent);
            }
        });
        return view;
    }
//    // 打开系统相册
//    private void openGallery() {
//
//        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        intent.setType("image/*");
//        startActivityForResult(intent, Constants.GALLERY_REQUEST_CODE);
//    }
//
//    // 处理相册返回结果
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//        if (requestCode == Constants.GALLERY_REQUEST_CODE && resultCode == getActivity().RESULT_OK && data != null) {
//            Uri selectedImageUri = data.getData();
//            if (selectedImageUri != null) {
//                // 保存选择的头像
//                profileViewModel.saveNewAvatar(selectedImageUri);
//            }
//        }
//    }
    private void displayImageFromUri(Uri uri, ImageView imageView) {
        if (uri == null || imageView == null) return;

        // 1. 通过 ContentResolver 获取图片输入流
        try (InputStream inputStream = requireContext().getContentResolver().openInputStream(uri)) {
            // 2. 压缩图片（避免大图片导致 OOM）
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 2;  // 宽高都压缩为原来的 1/2，可根据需求调整
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);

            // 3. 显示到 ImageView（若需圆形头像，需额外处理）
            imageView.setImageBitmap(bitmap);

        } catch (FileNotFoundException e) {
            // 处理异常（如图片被删除）
            e.printStackTrace();
            imageView.setImageResource(R.mipmap.ic_launcher);  // 显示默认头像
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 初始化相册选择器（之前的代码，保持不变）
    private void initGalleryLauncher() {
        galleryLauncher = registerForActivityResult(
                new ActivityResultContracts.GetContent(),
                selectedImageUri -> {
                    if (selectedImageUri != null) {
                        profileViewModel.saveNewAvatar(selectedImageUri);
                    }
                }
        );
    }
    // 初始化权限申请器：处理权限申请结果
    private void initPermissionLauncher() {
        permissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (isGranted) {
                        // 权限申请通过，打开相册
                        openGallery();
                    } else {
                        // 权限被拒绝，提示用户（可选：引导用户去设置页开启）
                        Toast.makeText(requireContext(),
                                "需要存储权限才能选择头像",
                                Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }
    // 检查权限并决定是否打开相册
    private void checkPermissionAndOpenGallery() {
        // 根据 Android 版本选择需要申请的权限
        String requiredPermission = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
                ? Manifest.permission.READ_MEDIA_IMAGES  // Android 13+ 用细分权限
                : Manifest.permission.READ_EXTERNAL_STORAGE;  // Android 12 及以下

        // 检查是否已有权限
        if (ContextCompat.checkSelfPermission(requireContext(), requiredPermission)
                == PackageManager.PERMISSION_GRANTED) {
            // 已有权限，直接打开相册
            openGallery();
        } else {
            // 无权限，发起申请
            permissionLauncher.launch(requiredPermission);
        }
    }
    // 打开相册（之前的代码，保持不变）
    private void openGallery() {
        galleryLauncher.launch("image/*");
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "onActivityCreated: Activity创建完成");
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: Fragment可见");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: Fragment可交互");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: Fragment失去焦点");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: Fragment不可见");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView: 视图销毁");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: Fragment销毁");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "onDetach: 与Activity解除关联");
//        infoSavedListener = null; // 避免内存泄漏
    }

}